#Get objects
old_ws = ls()


############
#Spillovers#
############
all_podes = mergedTable_podes[!is.na(Violence_1_count)]
all_nvms = mergedTable_nvms[!is.na(NVM_Violence_1_count)]

#Identified Spillovers Test
###########################

#Collapse kabupaten to dapils WITHOUT close runoff between islamists/nonislamists
spillover_podes = all_podes[, list(close_count = sum(sample_ni_it),
                 close_wins = sum(sample_ni_it & IT_win),
                 total_seats = sum(dapil_seats),
                 it_seats = sum(all_IT_seats),
                 Violence_1_deaths = sum(Violence_1_deaths[!(sample_ni_it)]),
                 Violence_1_count = sum(Violence_1_count[!(sample_ni_it)]),
                 Violence_1_binary = sum(Violence_1_count[!(sample_ni_it)]) > 0,
                 Violence_1_deaths_binary = sum(Violence_1_deaths[!(sample_ni_it)]) > 0,
                 count = .N)
                 , by = list(id_kab, election_cycle)]

spillover_nvms = all_nvms[, list(close_count = sum(sample_ni_it),
                                   close_wins = sum(sample_ni_it & IT_win),
                                   total_seats = sum(dapil_seats),
                                   it_seats = sum(all_IT_seats),
                                   Violence_1_deaths = sum(NVM_Violence_1_deaths[!(sample_ni_it)]),
                                   Violence_1_count = sum(NVM_Violence_1_count[!(sample_ni_it)]),
                                   Violence_1_deaths_binary = sum(NVM_Violence_1_deaths[!(sample_ni_it)]) > 0,
                                   Violence_1_binary = sum(NVM_Violence_1_count[!(sample_ni_it)]) > 0,
                                   count = .N)
                            , by = list(id_kab, election_cycle)]


spillover_nvms[, s_control := paste(close_count, total_seats, sep = ":")]
spillover_podes[, s_control := paste(close_count, total_seats, sep = ":")]
spillover_nvms[, control := close_count / total_seats]
spillover_podes[, control := close_count / total_seats]
spillover_nvms[, close_win_pct := close_wins / total_seats]
spillover_podes[, close_win_pct := close_wins / total_seats]

#NVMS

#Model specifications
nb_specs = expand.grid(x = 'close_win_pct + control', y = c('Violence_1_count', 'Violence_1_deaths'), stringsAsFactors = F)
lm_specs = expand.grid(x = 'close_win_pct + control', y = c('Violence_1_binary', 'Violence_1_deaths_binary'), stringsAsFactors = F)

#Estimate models
nvms_nb_models = Map(function(y,x) glmnb_loop(y,x, spillover_nvms[close_count > 0]),
                     nb_specs$y, nb_specs$x)

nvms_lm_models = Map(function(y,x) lm_loop(y,x,  spillover_nvms[close_count > 0]),
                     lm_specs$y, lm_specs$x)

nvms_list = c(nvms_nb_models, nvms_lm_models)
nvms_se = lapply(nvms_list, function(x) vcovHC(x, type = 'HC1') %>% diag %>% sqrt)


#PODES

#Estimate models
podes_nb_models = Map(function(y,x) glmnb_loop(y,x, spillover_podes[close_count > 0]),
                      nb_specs$y, nb_specs$x)

podes_lm_models = Map(function(y,x) lm_loop(y,x,  spillover_podes[close_count > 0]),
                      lm_specs$y, lm_specs$x)

podes_list = c(podes_nb_models, podes_lm_models)
podes_se = lapply(podes_list, function(x) vcovHC(x, type = 'HC1') %>% diag %>% sqrt)

##############
#create table#
##############

table_list = c(podes_list,nvms_list)
table_se = c(podes_se,nvms_se)

n_clusters = spillover_nvms[close_count > 0] %>% nrow
n_clusters_2 = spillover_podes[close_count > 0] %>% nrow

note_text = paste("Count models use negative binomial regression; binary outcomes use OLS.  Standard errors are robust. In the NVMS and PODES samples, there are ", n_clusters, "and ", n_clusters_2, " districts, respectively. Observations are kabupaten in which the last seat was contested by Islamist and secular nationalist parties with a margin less than 1 percent in at least one constituency.")

table = stargazer(table_list, se = table_se, type = 'latex', 
                  title = "Estimated Effects of Islamist Close Victories on Religious Violence (In-district Spillovers)",
                  label = 'tab:spillover_violence_identified_ni_it',
                  model.names = F,
                  model.numbers = T,
                  column.separate = c(4,4),
                  column.labels = c('PODES', 'NVMS'),
                  multicolumn = T,
                  dep.var.labels = rep(c("Events","Deaths"), 4), 
                  add.lines = list(c('Count', rep(c('Y', 'Y', 'N', 'N'), 2)),
                                   c('Binary', rep(c('N', 'N', 'Y', 'Y'), 2))),
                  covariate.labels = c("Close Islamist Win (\\% of seats)", 'Close Islamist Win or Lose (\\% of seats)'),
                  star.cutoffs = c(0.1, 0.05, 0.01),
                  keep = c('close_win_pct', 'control'),
                  #float.env = 'sidewaystable',
                  notes.align = 'l',
                  font.size = 'scriptsize',
                  keep.stat = 'n',
                  style = 'apsr')

write_latex(table[-10] %>% append(table[10], after = 10) %>% append("\\cmidrule(lr){2-5}\\cmidrule(lr){6-9}", after = 10), note_text, './output/tables/table_e4.tex')

#cleanup
drop = setdiff(ls(), c(old_ws)) 
rm(list = drop)